//封装加载
async function loadMessages(){
    // 发送GET请求到服务器
    await axios({
        url: "/api/messages",
        method: "get"
    }).then(res=>{
        let data = res.data;
        let listEle = document.querySelector("#list");
        // 清空列表内容
        listEle.innerHTML = "";
        // 添加留言到列表中
        console.log(data);
        data.forEach(item=>{
            let liEle = document.createElement("li");
            liEle.style.height = "auto";
            liEle.innerHTML = "<h2 class='user'>" + item.username + "说:</h2>" +
                "<p>" + item.message + "</p>" +
                "<a href='javascript:;' class='clos' id='"+ item._id +"'>删除</a>" +
                '<a href="javascript:;" class="clos2" >回复</a>' +
                "<p style='display:none'><input type='text' /><button class='sure' id='"+ item._id +"'>确定</button><button class='cancel'>取消</button></p>" 
            if (item.replies) {
                item.replies.forEach(item=>{liEle.innerHTML += `<p>${item}</p>`})
            }
            listEle.appendChild(liEle);
        })
    }).catch(err=>{
        console.log(error);
    })
    await del();
    await replay();
    await cancel();
    await sure();
}
//删除
function del() {
    let delBtn = document.querySelectorAll(".clos");
    delBtn.forEach(item=>{
        
        item.onclick = function () {
            let id = item.getAttribute("id");
            this.parentElement.remove();
            axios({
                url: "/api/messages",
                method: "delete",
                data: {
                    _id:id
                }
            }).then(res=>{
                loadMessages();
            }).catch(err=>{
                console.log(error);
            })
        }
    })  
}
// 点击回复 显示 回复的对话框
function replay() {
    let replayEle = document.querySelectorAll(".clos2");
    replayEle.forEach(item=>{
        item.onclick = function () {
            this.nextElementSibling.style.display = "block";
        }
    })  
}
// 获取取消按钮 
function cancel() {
    let cancelEle = document.querySelectorAll(".cancel");
    cancelEle.forEach(item=>{
        item.onclick = function(){
            this.parentElement.style.display = "none";
        }
    }) 
}
// 点击确定回复 
function sure() {
    let sureEle = document.querySelectorAll(".sure");
    sureEle.forEach(item=>{
        item.onclick = function(){
            let id = item.getAttribute("id");
            // 获取 输入的内容
            let val = this.previousElementSibling.value;
            // this.parentElement.style.display = "none";
            axios({
                url: "/api/replies",
                method: "post",
                data: {
                    val,
                    id
                }
            }).then(res=>{
                loadMessages();
            }).catch(err=>{
                console.log(error);
            })
        }
    }) 
}
